const express = require("express")
const app = express()
const fs = require("fs")
const os = require("os")
const { resolve } = require('path')
const port = process.env.port || process.env.npm_config_port || process.env.NODE_ENV === 'dev' ? 3000  : 9097// 端口

const JSONFILE = './local.bak.json';
const MSG = {
  success: {
    code: '0',
    message: 'success'
  }
}
app.use(express.json());
app.use(express.urlencoded({ extended: false }));


app.use("/getSysList", async (req, res) => {
  console.log(req.originalUrl)
  const data = readFile().map(item => item.sys)
  res.json({
    ...MSG.success,
    data
  });
});


app.use("/getJsonData", async (req, res) => {
  const { pageNum: page, pageSize: size, _t, ...rest} = req.query
  let data = readFile(), total = data.length
  let resData
  if (Object.keys(rest).length) {
    resData = filterData(rest, data), total = resData.length;
    resData = resData.splice((page - 1) * size, size)
  } else {
    resData = data.splice((page - 1) * size, size)
  }
 
  res.json({
    ...MSG.success,
    data: resData,
    total
  });
});

app.use("/saveJsonData", async (req, res) => {
  const data = JSON.stringify(req.body);
  // const data = Buffer.from(JSON.stringify(res.body))
  // fs.copyFile('./public/local.json', './local.bak.json', err => {
  //   if (err) console.log('something err.')
  //   else  console.log('copry file success.')
  // })
  // let origin = fs.createReadStream('./public/local.json')
  // let out = fs.createWriteStream('./local.bak.json')
  // origin.pipe(out)
  save(data)
  console.log('save success.')
  res.json(MSG.success);
});

app.use("/delJsonData", async (req, res) => {
  const { id } = req.body
  const bak = readFile()
  bak.splice(bak.findIndex(id => id), 1)
  writeContxt(bak);
  res.json(MSG.success)
})

app.use("/editJsonData", async (req, res) => {
  const { id, _t, ...rest } = req.body
  const bak = readFile()
  let index = bak.findIndex(item => item.id === id)
  bak[index] = { id, ...rest }
  writeContxt(bak);
  res.json(MSG.success)
})

function save(data) {
  data = JSON.parse(data);
  const bak = readFile()
  bak.unshift({id: bak.length + 1, ...data})
  writeContxt(bak)
}

function readFile() {
  return  JSON.parse(fs.readFileSync(resolve(__dirname, JSONFILE), 'utf-8'))
}

function writeContxt(data) {
  const o = JSON.stringify(data)
   // os.EOL 换行符
   fs.writeFileSync(JSONFILE, o + os.EOL);
}

function filterData(field, data) {
  let res = data
  Object.keys(field).forEach((item) => {
    if (field[item]) {
      res = res.filter(f => f[item] == field[item])
    }
  })
  return res;
}


app.listen(port, () => console.log(`running at ${port}...`))